package com.example.sunny.service.backgroundservice

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.*
import com.example.sunny.R
import com.example.sunny.SunnyApplication.Companion.context
import com.example.sunny.pojo.location.MyLocation
import com.example.sunny.pojo.weather.Weather
import com.example.sunny.pojo.weather.getSky
import com.example.sunny.service.Repository
import com.example.sunny.service.network.location.LocationService
import com.example.sunny.view.weather.WeatherActivity
import kotlin.concurrent.thread

class AlarmService : Service(),LocationService.MyLocationListener.LocationCallback{

    var myLocation=MutableLiveData<MyLocation>()

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("AlarmService","启动alarmService")
        //获得定位
        val locationClient = LocationService.initLocation(context, this)
        locationClient.requestLocation()

        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channel = NotificationChannel("weather","天气",NotificationManager.IMPORTANCE_DEFAULT)
        manager.createNotificationChannel(channel)


        val weatherLiveData  =Transformations.switchMap(myLocation){
            Repository.refreshWeather(it?.lng.toString(),it?.lat.toString(), context)
        }

        val observer = Observer<Result<Weather>> { result->
            val weather = result.getOrNull()
            if (weather!=null) {
                myLocation.apply {
                    val temperature = weather.daily.temperature[0].run {
                        "${min.toInt()}~${max.toInt()} ℃"
                    }
                    val skycon = getSky(weather.daily.skycon[0].value).info
                    val cintent = Intent(context, WeatherActivity::class.java)
                    val pendingIntent = PendingIntent.getActivity(context, 0, cintent, PendingIntent.FLAG_UPDATE_CURRENT)

                    val notification = NotificationCompat.Builder(context, "weather")
                        .setContentTitle("桑尼向您推送今天的天气~")
                        .setContentText("${myLocation.value!!.city} 天气:${skycon} 温度:${temperature}")
                        .setSmallIcon(R.drawable.ic_clear_day)
                        .setLargeIcon(BitmapFactory.decodeResource(resources, getSky(weather.daily.skycon[0].value).icon))
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .build()

                    manager.notify(1, notification)
                    Log.d("AlarmService","通知已推送")

                }
            }
        }
        weatherLiveData.observeForever(observer)
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }


    override fun onDestroy() {
        super.onDestroy()

    }

    override fun getLocation(myLocation: MyLocation) {
        Log.d("AlarmService","更新位置")
        this.myLocation.value = myLocation
    }



}